<template>
  <div class="vcWrap">
    <input
      type="text"
      v-for="n in 4"
      :key="'codeInput' + n"
      :ref="'codeInput' + n"
      maxlength="1"
      @keydown.stop="nextInput($event, n)"
      v-model="codeArray[n - 1]"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      codeArray: [],
      keyCodes: [
        48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102,
        103, 104, 105, 13, 32, 8,
      ],
    };
  },
  methods: {
    nextInput(e, n) {
      console.log(e);
      if (this.keyCodes.includes(e.keyCode)) {
        if (
          (e.keyCode >= 48 && e.keyCode <= 57) ||
          (e.keyCode >= 96 && e.keyCode <= 105)
        ) {
          console.log("数组长度：", this.codeArray.length);
          if (n <= 4 && this.codeArray.length < 4) {
            console.log("第" + n + "个");
            e.returnValue = false;
            this.codeArray.push(e.key);
            n == 4 ? null : this.$refs[`codeInput${n + 1}`][0].focus();
          }
        }
        if (e.keyCode == 8) {
          e.returnValue = false;
          n - 1 > 0 ? this.$refs[`codeInput${n - 1}`][0].focus() : null;
          this.codeArray.pop();
        }
      } else {
        e.returnValue = false;
      }
      console.log(this.codeArray);
    },
  },
};
</script>

<style lang="less">
.vcWrap {
  input {
    display: inline-block;
    width: 40px;
    height: 40px;
    line-height: 40px;
    -webkit-appearance: none;

    outline: 0;
    font-size: 20px;
    text-align: center;
    background-color: #eee;
    border: 1px solid #eee;
    box-sizing: border-box;
    font-size: inherit;
    padding: 0 14px;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    border-radius: 4px;
    margin-right: 1em;
  }
  input:last-child {
    margin-right: 0;
  }
}
</style>